package com.gitee.l0km.xthrift.base.doc;

import java.util.concurrent.ConcurrentHashMap;

import com.gitee.l0km.com4j.basex.doc.ClassCommentProvider;
import static com.google.common.base.Preconditions.checkNotNull;
import static com.google.common.base.Preconditions.checkState;
import static com.gitee.l0km.xthrift.base.metadata.Decorators.javadocCommentProviderFactory;

/**
 * @author guyadong
 * @since 2.4.0
 */
public class CommentProviderFactories {
	/**
	 * {@link ClassCommentProvider}实例缓存
	 */
	private static final ConcurrentHashMap<Class<?>, ClassCommentProvider> PROVIDER_CACHE = new ConcurrentHashMap<>();

	/**
	 * 返回指定类型基于代理类型优先(Delegate Firstly)策略实现的{@link ClassCommentProvider}接口实例<br>
	 * 当{@link com.gitee.l0km.xthrift.base.metadata.Decorators#javadocCommentProviderFactory}
	 * 无效时抛出{@link IllegalStateException}异常
	 * 
	 * @see DelegateFirstlyProvider
	 * 
	 * @param clazz
	 */
	public static ClassCommentProvider providerOf(Class<?> clazz) {
		ClassCommentProvider provider = PROVIDER_CACHE.get(checkNotNull(clazz, "clazz is null"));
		if (provider != null) {
			return provider;
		}
		checkState(withValidFactory(), "Decorators.javadocCommentProviderFactory is null");
		provider = new DelegateFirstlyProvider(javadocCommentProviderFactory,clazz);
		PROVIDER_CACHE.putIfAbsent(clazz, provider);
		return provider;
	}

	/**
	 * 返回指定类型基于代理类型优先(Delegate Firstly)策略实现的{@link ClassCommentProvider}接口实例<br>
	 * 当{@link com.gitee.l0km.xthrift.base.metadata.Decorators#javadocCommentProviderFactory}
	 * 无效时返回{@code null}
	 * 
	 * @see DelegateFirstlyProvider
	 * @param clazz
	 */
	public static ClassCommentProvider providerOrNullOf(Class<?> clazz) {
		return withValidFactory() ? providerOf(clazz) : null;
	}

	/**
	 * 判断{@link com.gitee.l0km.xthrift.base.metadata.Decorators#javadocCommentProviderFactory}是否有效<br>
	 * 不为{@code null}返回{@code true}
	 */
	public static boolean withValidFactory() {
		return javadocCommentProviderFactory != null;
	}
}
